<template>
  <div id="app">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card class="box-card">
      <!-- 卡片头部区域 -->
      <div slot="header" class="clearfix">
        <!-- 警告提示文案 -->
        <el-alert title="注意：用户名不可更改！" type="warning" show-icon>
        </el-alert>
        <!-- 搜索与添加区域 -->
        <el-row :gutter="20">
          <el-col :span="9">
            <el-input
              placeholder="请输入内容"
              class="input-with-select"
              v-model="queryInfo.query"
              clearable
              @clear="getUserList"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUserList"
              ></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="adddialogVisible = true"
              >添加用户</el-button
            >
          </el-col>
        </el-row>
      </div>
      <!-- 用户列表数据区域 -->
      <el-table :data="userList" border stripe>
        <!-- 第一行利用type加上index做成了索引列 -->
        <el-table-column type="index"></el-table-column>
        <!-- 用prop属性来对应对象中的键名即可填入数据，用label属性来定义表格的列名 -->
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" width="100px">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="delUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="更改角色"
              placement="top"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="changeRoleInfo(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="adddialogVisible"
      width="50%"
      @close="closedUserForm"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addUserForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item prop="username" label="用户名">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editdialogVisible"
      width="30%"
      @close="editDialogClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="editUserForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="80px"
      >
        <!-- 数据库相应数据没有用户名，意味着用户名不可更改 -->
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配用户角色"
      :visible.sync="changeRoleDialogVisible"
      width="50%"
      @close="changeRoleDialogClosed"
    >
      <!-- 内容区域 -->
      <div>
        <p>{{ role.username }}</p>
        <p>{{ role.role_name }}</p>
      </div>
      <!-- 选择角色区域 -->
      <p>
        分配角色：
        <el-select v-model="saveRole" placeholder="请选择">
          <el-option
            v-for="item in roleLists"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    //自定义规则——邮箱
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0_9-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    //自定义规则——手机号
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法手机号'))
    }
    return {
      // 请求用户数据参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 总条数
      total: 0,
      // 用户数据列表
      userList: [],
      //添加用户对话框表单数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 控制添加用户对话框的显示与隐藏
      adddialogVisible: false,
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 6, message: '用户名在3到6个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码在6到12字符之间', trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' },
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        mobile: [
          { validator: checkMobile, trigger: 'blur' },
          { required: true, message: '请输入手机号码', trigger: 'blur' }
        ]
      },
      // 查询到的用户信息对象
      editUserForm: {},
      // 控制修改用户对话框的显示与隐藏
      editdialogVisible: false,
      editFormRules: {
        email: [
          { validator: checkEmail, trigger: 'blur' },
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        mobile: [
          { validator: checkMobile, trigger: 'blur' },
          { required: true, message: '请输入手机号码', trigger: 'blur' }
        ]
      },
      // 控制分配角色对话框的显示与隐藏
      changeRoleDialogVisible: false,
      // 分配角色获取的用户基本信息
      role: {},
      // 获取的角色信息
      roleLists: [],
      // 用户选择新的角色信息
      saveRole: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户管理列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // pageSize 每页条数改变时会触发的事件
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    // currentPage 页码改变时会触发的事件
    handleCurrentChange(newpage) {
      this.queryInfo.pagenum = newpage
      this.getUserList()
    },
    //验证规则&提交添加用户表单数据
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.adddialogVisible = false
        this.getUserList()
      })
    },
    // 添加用户表单重置功能
    closedUserForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 编辑用户根据id获取相应信息
    async showEditDialog(row) {
      const { data: res } = await this.$http.get('users/' + row)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editUserForm = res.data
      this.editdialogVisible = true
    },
    //验证规则&提交编辑用户表单数据
    editUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editUserForm.id,
          {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('编辑用户信息失败')
        }
        this.getUserList()
        this.$message.success('编辑用户信息成功')
        this.editdialogVisible = false
      })
    },
    //编辑用户每次数据变动的验证结果被重置
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 提示用户&删除用户
    async delUserById(row) {
      const delresult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (delresult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      const { data: res } = await this.$http.delete('users/' + row)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getUserList()
    },
    //点击分配角色按钮，获取角色信息
    async changeRoleInfo(role) {
      //用户基本信息
      this.role = role
      // 获取角色信息
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败')
      }
      this.roleLists = res.data
      this.changeRoleDialogVisible = true
    },
    // 提交分配角色信息
    async changeRoles() {
      // 判断用户是否选择了角色
      if (!this.saveRole) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.role.id}/role`, {
        rid: this.saveRole
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.getUserList()
      this.changeRoleDialogVisible = false
      this.$message.success('分配角色成功')
    },
    // 监听分配角色对话框的关闭事件
    changeRoleDialogClosed() {
      this.saveRole = ''
      this.roleLists = []
    }
  }
}
</script>
<style lang="less" scoped>
.el-row {
  margin: 15px 0 0;
  font-size: 15px;
  span {
    line-height: 40px;
  }
}
</style>
